import re
from typing import Optional
from urllib.parse import urlparse


class PlatformDetector:
    """视频平台检测器"""
    
    def __init__(self):
        """初始化平台检测规则"""
        self.platform_patterns = {
            "douyin": [
                r"douyin\.com",
                r"iesdouyin\.com", 
                r"dy\.app",
                r"v\.douyin\.com"
            ],
            "tiktok": [
                r"tiktok\.com",
                r"vm\.tiktok\.com",
                r"vt\.tiktok\.com",
                r"t\.tiktok\.com"
            ],
            "bilibili": [
                r"bilibili\.com",
                r"b23\.tv",
                r"bili\.li"
            ]
        }
    
    def detect_platform(self, url: str) -> Optional[str]:
        """
        检测视频链接所属平台
        
        Args:
            url: 视频链接
            
        Returns:
            str: 平台代码 (douyin, tiktok, bilibili) 或 None
        """
        if not url:
            return None
            
        try:
            # 标准化URL
            url = self._normalize_url(url)
            
            # 解析域名
            parsed = urlparse(url)
            domain = parsed.netloc.lower()
            
            # 匹配平台
            for platform, patterns in self.platform_patterns.items():
                for pattern in patterns:
                    if re.search(pattern, domain):
                        return platform
            
            return None
            
        except Exception:
            return None
    
    def _normalize_url(self, url: str) -> str:
        """标准化URL格式"""
        url = url.strip()
        
        # 添加协议
        if not url.startswith(("http://", "https://")):
            url = "https://" + url
            
        return url
    
    def is_supported_platform(self, url: str) -> bool:
        """检查是否为支持的平台"""
        return self.detect_platform(url) is not None
    
    def get_platform_info(self, platform: str) -> dict:
        """获取平台详细信息"""
        platform_info = {
            "douyin": {
                "name": "抖音",
                "name_en": "Douyin",
                "description": "字节跳动旗下短视频平台",
                "domains": ["douyin.com", "iesdouyin.com"],
                "country": "CN"
            },
            "tiktok": {
                "name": "TikTok",
                "name_en": "TikTok", 
                "description": "字节跳动国际版短视频平台",
                "domains": ["tiktok.com"],
                "country": "Global"
            },
            "bilibili": {
                "name": "哔哩哔哩",
                "name_en": "Bilibili",
                "description": "中国领先的年轻人文化社区",
                "domains": ["bilibili.com", "b23.tv"],
                "country": "CN"
            }
        }
        
        return platform_info.get(platform, {})
    
    def extract_video_id(self, url: str, platform: str) -> Optional[str]:
        """
        从URL中提取视频ID
        
        Args:
            url: 视频链接
            platform: 平台类型
            
        Returns:
            str: 视频ID 或 None
        """
        try:
            if platform == "douyin":
                return self._extract_douyin_id(url)
            elif platform == "tiktok":
                return self._extract_tiktok_id(url)
            elif platform == "bilibili":
                return self._extract_bilibili_id(url)
            else:
                return None
        except Exception:
            return None
    
    def _extract_douyin_id(self, url: str) -> Optional[str]:
        """提取抖音视频ID"""
        patterns = [
            r'/video/(\d+)',
            r'aweme_id=(\d+)',
            r'item_id=(\d+)',
            r'/(\d+)/?(?:\?|$)'
        ]
        
        for pattern in patterns:
            match = re.search(pattern, url)
            if match:
                return match.group(1)
        return None
    
    def _extract_tiktok_id(self, url: str) -> Optional[str]:
        """提取TikTok视频ID"""
        patterns = [
            r'/video/(\d+)',
            r'@[\w.]+/video/(\d+)',
            r'/(\d+)/?(?:\?|$)'
        ]
        
        for pattern in patterns:
            match = re.search(pattern, url)
            if match:
                return match.group(1)
        return None
    
    def _extract_bilibili_id(self, url: str) -> Optional[str]:
        """提取哔哩哔哩视频ID"""
        # BV号匹配
        bv_match = re.search(r'(BV[a-zA-Z0-9]+)', url)
        if bv_match:
            return bv_match.group(1)
        
        # av号匹配
        av_match = re.search(r'av(\d+)', url)
        if av_match:
            return f"av{av_match.group(1)}"
        
        return None
    
    def validate_url(self, url: str) -> dict:
        """
        验证URL的有效性
        
        Returns:
            dict: 验证结果
        """
        result = {
            "valid": False,
            "platform": None,
            "video_id": None,
            "error": None
        }
        
        try:
            if not url:
                result["error"] = "URL为空"
                return result
            
            # 检测平台
            platform = self.detect_platform(url)
            if not platform:
                result["error"] = "不支持的视频平台"
                return result
            
            result["platform"] = platform
            
            # 提取视频ID
            video_id = self.extract_video_id(url, platform)
            if not video_id:
                result["error"] = "无法提取视频ID"
                return result
            
            result["video_id"] = video_id
            result["valid"] = True
            
        except Exception as e:
            result["error"] = f"URL验证失败: {str(e)}"
        
        return result